//
//  EventListenerHelper.m
//  aloqa
//
//  Created by mkoo sun on 12-8-27.
//  Copyright (c) 2012年 mogenesis. All rights reserved.
//

#import "EventListenerHelper.h"

@implementation EventStub

@synthesize eventid;
@synthesize stub;
@synthesize count; 

//-------------------------------------------------------------------------------------------
- (id)initWithID:(NSString*)_eventid stub:(int)_stub 
{
    self = [super init];
    if (self) {
        self.eventid = _eventid;
        self.stub = _stub;
        self.count = 1;
    }
    return self;
}

- (void)dealloc
{
    //MCRelease(eventid);
    eventid = nil;
}

//-------------------------------------------------------------------------------------------
+ (id) create:(NSString*)eventid stub:(int)stub
{
    EventStub* eventStub = [[[EventStub alloc]initWithID:eventid stub:stub] autorelease];
    return eventStub;
}

@end

//-------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------

@implementation EventListenerHelper

@synthesize service;
@synthesize stubs;

- (id)init
{
    self = [super init];
    if (self) {
        stubs = [[NSMutableDictionary alloc]init];
    }
    return self;
}

- (void)dealloc
{
    [service release];
    [stubs release];
    service = nil;
    stubs = nil;
    [super dealloc];
}

//- (EventService*) getService
//{
//    return service;
//}

//- (void) setService:(EventService*) service
//{
//    self.service = service;
//}

- (int) attahEvent:(NSString*)eventid
{
    EventStub* stub = Nil;
    
    stub = [stubs objectForKey:eventid];
    if (stub != Nil)
    {
        ++stub.count;
        return stub.stub;
    }
    
    int result = [service registerEventListener:eventid listener:self];
        
    stub = [EventStub create:eventid stub:result];

    [stubs setValue:stub forKey:eventid];
    
    return stub.stub;
}

- (void) detachEvent:(NSString*)eventid
{
    EventStub* stub = [stubs objectForKey:eventid];
    
    if (stub != nil && --stub.stub == 0)
    {
        [service unregisterEventListener:stub.eventid stub:stub.stub];
        [stubs removeObjectForKey:eventid];
    }
}

-(void) onEvent:(NSString*)event_id param1:(NSString*)param1 param2:(NSString*)param2
{
    //exit(0);
}
@end
